<template>
  <div class="course-list-container">
    <el-card class="box-card">
      <template #header>
        <div class="clearfix">
          <span>课程管理</span>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form
        :model="searchForm"
        ref="searchFormRef"
        :inline="true"
        label-width="80px"
        class="search-form"
      >
        <el-form-item label="课程名称" prop="keyword">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入课程名称"
            clearable
            style="width: 200px"
            @keyup.enter="searchCourses"
          />
        </el-form-item>
        <el-form-item label="课程分类" prop="category">
          <el-select
            v-model="searchForm.category"
            placeholder="请选择课程分类"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="option in categoryOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程状态" prop="status">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择课程状态"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="option in statusOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchCourses">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>

      <div class="action-buttons">
        <el-button type="primary" @click="openAddDialog">
          <el-icon><Plus /></el-icon>新增课程
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
        <el-button @click="downloadData">
          <el-icon><Download /></el-icon>导出
        </el-button>
        <el-button @click="showFilter">
          <el-icon><Filter /></el-icon>筛选
        </el-button>
      </div>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="courseList"
        style="width: 100%;"
        border
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="name" label="课程名称" width="200">
          <template #default="{ row }">
            <span @click="viewCourseDetail(row.id)" class="course-name-link">{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="code" label="课程代码" width="120" align="center" />
        <el-table-column prop="categoryName" label="课程分类" width="120" align="center" />
        <el-table-column prop="teacher" label="教师" width="120" align="center" />
        <el-table-column prop="credit" label="学分" width="80" align="center" />
        <el-table-column prop="price" label="价格(¥)" width="100" align="center" />
        <el-table-column prop="startTime" label="开始时间" width="180" align="center" :formatter="formatDate" />
        <el-table-column prop="endTime" label="结束时间" width="180" align="center" :formatter="formatDate" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag
              :type="row.status === '进行中' ? 'success' : row.status === '已结束' ? 'info' : 'warning'"
            >
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="openEditDialog(row)">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button type="success" size="small" @click="manageChapters(row.id)">
              <el-icon><Document /></el-icon> 章节
            </el-button>
            <el-button type="danger" size="small" @click="deleteCourse(row.id)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑课程" width="600px">
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="课程代码" prop="code">
          <el-input v-model="editForm.code" placeholder="请输入课程代码" />
        </el-form-item>
        <el-form-item label="课程分类" prop="category">
          <el-select v-model="editForm.category" placeholder="请选择课程分类">
            <el-option v-for="option in categoryOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="教师" prop="teacher">
          <el-select v-model="editForm.teacher" placeholder="请选择教师">
            <el-option v-for="option in teacherOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="学分" prop="credit">
          <el-input v-model.number="editForm.credit" type="number" placeholder="请输入学分" />
        </el-form-item>
        <el-form-item label="价格(¥)" prop="price">
          <el-input v-model.number="editForm.price" type="number" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="editForm.startTime" type="date" placeholder="请选择开始时间" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker v-model="editForm.endTime" type="date" placeholder="请选择结束时间" />
        </el-form-item>
        <el-form-item label="课程状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择课程状态">
            <el-option v-for="option in statusOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程描述" prop="description">
          <el-input v-model="editForm.description" type="textarea" :rows="3" placeholder="请输入课程描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeEditDialog">取消</el-button>
        <el-button type="primary" @click="saveEdit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 新增对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增课程" width="600px">
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="课程代码" prop="code">
          <el-input v-model="addForm.code" placeholder="请输入课程代码" />
        </el-form-item>
        <el-form-item label="课程分类" prop="category">
          <el-select v-model="addForm.category" placeholder="请选择课程分类">
            <el-option v-for="option in categoryOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="教师" prop="teacher">
          <el-select v-model="addForm.teacher" placeholder="请选择教师">
            <el-option v-for="option in teacherOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="学分" prop="credit">
          <el-input v-model.number="addForm.credit" type="number" placeholder="请输入学分" />
        </el-form-item>
        <el-form-item label="价格(¥)" prop="price">
          <el-input v-model.number="addForm.price" type="number" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="addForm.startTime" type="date" placeholder="请选择开始时间" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker v-model="addForm.endTime" type="date" placeholder="请选择结束时间" />
        </el-form-item>
        <el-form-item label="课程状态" prop="status">
          <el-select v-model="addForm.status" placeholder="请选择课程状态">
            <el-option v-for="option in statusOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程描述" prop="description">
          <el-input v-model="addForm.description" type="textarea" :rows="3" placeholder="请输入课程描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeAddDialog">取消</el-button>
        <el-button type="primary" @click="saveAdd">确定</el-button>
      </template>
    </el-dialog>

    <!-- 章节管理对话框 -->
    <el-dialog v-model="chapterDialogVisible" title="章节管理" width="800px">
      <div class="chapter-management">
        <div class="chapter-list">
          <el-button type="primary" @click="openChapterEditDialog(null)" style="margin-bottom: 15px;">
            <el-icon><Plus /></el-icon> 添加章节
          </el-button>
          
          <el-table :data="chapters" style="width: 100%;" border>
            <el-table-column prop="title" label="章节标题" />
            <el-table-column prop="description" label="描述" />
            <el-table-column label="操作" width="200">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="openChapterEditDialog(row)">编辑</el-button>
                <el-button type="success" size="small" @click="manageVideos(row.id)">视频</el-button>
                <el-button type="danger" size="small" @click="deleteChapterById(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="chapterDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 章节编辑对话框 -->
    <el-dialog v-model="chapterDialogVisible" title="编辑章节" width="500px">
      <el-form
        ref="chapterFormRef"
        :model="chapterForm"
        label-width="100px"
      >
        <el-form-item label="章节标题" prop="title">
          <el-input v-model="chapterForm.title" placeholder="请输入章节标题" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="chapterForm.description" type="textarea" :rows="3" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="chapterDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveChapter">确定</el-button>
      </template>
    </el-dialog>

    <!-- 视频管理对话框 -->
    <el-dialog v-model="videoDialogVisible" title="视频管理" width="800px">
      <div class="video-management">
        <div class="video-list">
          <el-button type="primary" @click="openVideoEditDialog(null)" style="margin-bottom: 15px;">
            <el-icon><Plus /></el-icon> 添加视频
          </el-button>
          
          <el-table :data="videos" style="width: 100%;" border>
            <el-table-column prop="title" label="视频标题" />
            <el-table-column prop="duration" label="时长(分钟)" />
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="openVideoEditDialog(row)">编辑</el-button>
                <el-button type="danger" size="small" @click="deleteVideoById(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="videoDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 视频编辑对话框 -->
    <el-dialog v-model="videoEditDialogVisible" title="编辑视频" width="500px">
      <el-form
        ref="videoFormRef"
        :model="videoForm"
        label-width="100px"
      >
        <el-form-item label="视频标题" prop="title">
          <el-input v-model="videoForm.title" placeholder="请输入视频标题" />
        </el-form-item>
        <el-form-item label="视频链接" prop="url">
          <el-input v-model="videoForm.url" placeholder="请输入视频链接" />
        </el-form-item>
        <el-form-item label="时长(分钟)" prop="duration">
          <el-input v-model.number="videoForm.duration" type="number" placeholder="请输入时长" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="videoEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveVideo">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElTable, ElTableColumn, ElButton, ElIcon, ElDialog, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElPagination, ElMessageBox, ElNotification, ElDatePicker, ElSwitch, ElTag, ElTree } from 'element-plus'
import { Search, Plus, Edit, Delete, Refresh, Download, Filter, Check, Close, Clock, Document, User } from '@element-plus/icons-vue'
import { getCoursePage, saveOrUpdateCourse, deleteCourses, getCourseById, getCourseCategories, saveOrUpdateCategory, deleteCategory, getCourseChapters, saveOrUpdateChapter, deleteChapter, getChapterVideos, saveOrUpdateVideo, deleteVideo } from '@/api/course'

// 课程列表数据
const courseList = ref([])
// 搜索表单
const searchForm = ref({
  keyword: '',
  category: '',
  status: ''
})
// 当前页码
const currentPage = ref(1)
// 每页条数
const pageSize = ref(10)
// 总条数
const total = ref(0)
// 加载状态
const loading = ref(false)
// 编辑对话框显示状态
const editDialogVisible = ref(false)
// 编辑表单数据
const editForm = ref({
  id: '',
  name: '',
  code: '',
  category: '',
  teacher: '',
  credit: '',
  startTime: '',
  endTime: '',
  status: '',
  description: '',
  price: 0,
  cover: ''
})
// 新增对话框显示状态
const addDialogVisible = ref(false)
// 新增表单数据
const addForm = ref({
  name: '',
  code: '',
  category: '',
  teacher: '',
  credit: '',
  startTime: '',
  endTime: '',
  status: '',
  description: '',
  price: 0,
  cover: ''
})
// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入课程代码', trigger: 'blur' }],
  category: [{ required: true, message: '请选择课程分类', trigger: 'change' }],
  teacher: [{ required: true, message: '请输入教师姓名', trigger: 'blur' }],
  credit: [
    { required: true, message: '请输入学分', trigger: 'blur' },
    { type: 'number', message: '学分必须是数字', trigger: 'blur' },
    { min: 1, max: 10, message: '学分必须在1-10之间', trigger: 'blur' }
  ],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  status: [{ required: true, message: '请选择课程状态', trigger: 'change' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }]
}
// 课程分类选项
const categoryOptions = ref([])
// 课程状态选项
const statusOptions = ref([
  { value: '未开始', label: '未开始' },
  { value: '进行中', label: '进行中' },
  { value: '已结束', label: '已结束' }
])
// 教师列表
const teacherOptions = ref([
  { value: '张老师', label: '张老师' },
  { value: '李老师', label: '李老师' },
  { value: '王老师', label: '王老师' },
  { value: '赵老师', label: '赵老师' },
  { value: '刘老师', label: '刘老师' }
])

// 章节管理相关
const chapterDialogVisible = ref(false)
const currentCourseId = ref('')
const chapters = ref([])
const chapterForm = ref({
  id: '',
  courseId: '',
  title: '',
  description: ''
})
const chapterFormRef = ref()

// 视频管理相关
const videoDialogVisible = ref(false)
const videoEditDialogVisible = ref(false)
const currentChapterId = ref('')
const videos = ref([])
const videoForm = ref({
  id: '',
  chapterId: '',
  title: '',
  url: '',
  duration: 0
})
const videoFormRef = ref()

// 加载课程列表
const loadCourseList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      keyword: searchForm.value.keyword,
      category: searchForm.value.category,
      status: searchForm.value.status
    }
    
    const res = await getCoursePage(params)
    courseList.value = res.records || []
    total.value = res.total || 0
  } catch (error) {
    ElNotification.error('获取课程列表失败')
    console.error('Failed to load course list:', error)
  } finally {
    loading.value = false
  }
}

// 加载分类
const loadCategories = async () => {
  try {
    const res = await getCourseCategories()
    categoryOptions.value = res.map(item => ({
      value: item.id,
      label: item.name
    }))
  } catch (error) {
    ElNotification.error('获取分类失败')
    console.error('Failed to load categories:', error)
  }
}

// 搜索课程
const searchCourses = () => {
  currentPage.value = 1
  loadCourseList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    keyword: '',
    category: '',
    status: ''
  }
  currentPage.value = 1
  loadCourseList()
}

// 刷新数据
const refreshData = () => {
  loadCourseList()
}

// 打开编辑对话框
const openEditDialog = async (row) => {
  try {
    const res = await getCourseById(row.id)
    editForm.value = { ...res }
    editDialogVisible.value = true
  } catch (error) {
    ElNotification.error('获取课程详情失败')
    console.error('Failed to get course detail:', error)
  }
}

// 关闭编辑对话框
const closeEditDialog = () => {
  editDialogVisible.value = false
}

// 保存编辑
const saveEdit = async () => {
  try {
    await saveOrUpdateCourse(editForm.value)
    ElNotification.success('编辑成功')
    closeEditDialog()
    loadCourseList()
  } catch (error) {
    ElNotification.error('编辑失败')
    console.error('Failed to save edit:', error)
  }
}

// 打开新增对话框
const openAddDialog = () => {
  addForm.value = {
    name: '',
    code: '',
    category: '',
    teacher: '',
    credit: '',
    startTime: '',
    endTime: '',
    status: '',
    description: '',
    price: 0,
    cover: ''
  }
  addDialogVisible.value = true
}

// 关闭新增对话框
const closeAddDialog = () => {
  addDialogVisible.value = false
}

// 保存新增
const saveAdd = async () => {
  try {
    await saveOrUpdateCourse(addForm.value)
    ElNotification.success('添加成功')
    closeAddDialog()
    loadCourseList()
  } catch (error) {
    ElNotification.error('添加失败')
    console.error('Failed to save add:', error)
  }
}

// 删除课程
const deleteCourse = async (id) => {
  try {
    const result = await ElMessageBox.confirm('确定要删除该课程吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    if (result === 'confirm') {
      await deleteCourses([id])
      ElNotification.success('删除成功')
      loadCourseList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElNotification.error('删除失败')
      console.error('Failed to delete course:', error)
    }
  }
}

// 批量删除
const batchDelete = async () => {
  // 实现批量删除逻辑
  ElNotification.info('批量删除功能开发中...')
}

// 下载数据
const downloadData = () => {
  ElNotification.info('数据下载中...')
  // 实际应用中这里应该实现数据导出功能
}

// 查看课程详情
const viewCourseDetail = (id) => {
  // 实际应用中这里应该跳转到课程详情页
  ElNotification.info('跳转到课程详情页')
}

// 管理课程章节
const manageChapters = async (courseId) => {
  currentCourseId.value = courseId
  try {
    const res = await getCourseChapters(courseId)
    chapters.value = res || []
    chapterDialogVisible.value = true
  } catch (error) {
    ElNotification.error('获取章节列表失败')
    console.error('Failed to load chapters:', error)
  }
}

// 打开章节编辑对话框
const openChapterEditDialog = (chapter) => {
  if (chapter) {
    chapterForm.value = { ...chapter }
  } else {
    chapterForm.value = {
      id: '',
      courseId: currentCourseId.value,
      title: '',
      description: ''
    }
  }
}

// 保存章节
const saveChapter = async () => {
  try {
    await saveOrUpdateChapter(chapterForm.value)
    ElNotification.success('保存成功')
    const res = await getCourseChapters(currentCourseId.value)
    chapters.value = res || []
  } catch (error) {
    ElNotification.error('保存失败')
    console.error('Failed to save chapter:', error)
  }
}

// 删除章节
const deleteChapterById = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该章节吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteChapter(id)
    ElNotification.success('删除成功')
    const res = await getCourseChapters(currentCourseId.value)
    chapters.value = res || []
  } catch (error) {
    if (error !== 'cancel') {
      ElNotification.error('删除失败')
      console.error('Failed to delete chapter:', error)
    }
  }
}

// 管理章节视频
const manageVideos = async (chapterId) => {
  currentChapterId.value = chapterId
  try {
    const res = await getChapterVideos(chapterId)
    videos.value = res || []
    videoDialogVisible.value = true
  } catch (error) {
    ElNotification.error('获取视频列表失败')
    console.error('Failed to load videos:', error)
  }
}

// 打开视频编辑对话框
const openVideoEditDialog = (video) => {
  if (video) {
    videoForm.value = { ...video }
  } else {
    videoForm.value = {
      id: '',
      chapterId: currentChapterId.value,
      title: '',
      url: '',
      duration: 0
    }
  }
}

// 保存视频
const saveVideo = async () => {
  try {
    await saveOrUpdateVideo(videoForm.value)
    ElNotification.success('保存成功')
    const res = await getChapterVideos(currentChapterId.value)
    videos.value = res || []
  } catch (error) {
    ElNotification.error('保存失败')
    console.error('Failed to save video:', error)
  }
}

// 删除视频
const deleteVideoById = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该视频吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteVideo(id)
    ElNotification.success('删除成功')
    const res = await getChapterVideos(currentChapterId.value)
    videos.value = res || []
  } catch (error) {
    if (error !== 'cancel') {
      ElNotification.error('删除失败')
      console.error('Failed to delete video:', error)
    }
  }
}

// 格式化日期
const formatDate = (row, column, cellValue) => {
  if (!cellValue) return ''
  return new Date(cellValue).toLocaleDateString()
}

// 分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadCourseList()
}

// 当前页变化
const handleCurrentChange = (current) => {
  currentPage.value = current
  loadCourseList()
}

// 显示筛选
const showFilter = () => {
  ElNotification.info('筛选功能开发中...')
}

// 页面加载时获取数据
onMounted(() => {
  loadCourseList()
  loadCategories()
})
</script>

<style scoped>
.course-list-container {
  padding: 20px;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: -10px;
  margin-bottom: 20px;
}

.course-name-link {
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
}

.chapter-management,
.video-management {
  padding: 20px 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>